<script setup lang="ts">
import welcome from '@/utils/welcome'
import { useUserStore } from '@/stores'
import { topicGetTopicListService } from '@/api/topic'
import { onMounted, ref, type Ref } from 'vue'
import { type NumberAnimationInst, useMessage } from 'naive-ui'
import { formatTime } from '@/utils/format'
import { CapsuleChart } from '@kjgl77/datav-vue3'
import * as echarts from 'echarts'
import { debounce } from '@/hooks/debounce'
import { announcementGetAnnouncementListService, announcementDeleteAnnouncementService } from '@/api/announcement'
import { DeleteOutlined } from '@vicons/antd'
import HomeDialog from '@/views/Home/components/HomeDialog.vue'
import '@/assets/image/avatar.jpg'

const userStore = useUserStore()
const message = useMessage()

//默认头像
const defaultAvatar = import.meta.env.VITE_DEFAULT_AVATAR_URL

//帖子信息
const topicData: Ref<Api.Topic.TopicInfo[]> = ref([])
//公告信息
const announcementData: Ref<Api.Announcement.AnnouncementInfo[]> = ref([])
const count: Ref<number> = ref(0)
const kindNumber: Ref<number> = ref(0)
//动画
const numberAnimationInstRef = ref<NumberAnimationInst | null>(null)
//柱状图数据
const capsuleData = ref<
  {
    name: string
    value: number
  }[]
>([])
//柱状图配置
const capsuleConfig = reactive({
  data: capsuleData.value,
  unit: '条',
  textColor: 'rgba(100, 108, 255, 0.5)',
  showValue: true
})
//饼图配置项
let myChart: echarts.ECharts | null = null
const pieRef = ref<HTMLElement | null>(null)
const pieData = ref<
  {
    name: string
    value: number
  }[]
>([])
const handleResize = debounce(() => {
  if (myChart) {
    myChart.resize()
  }
}, 200)
let option: {
  toolbox: {
    feature: {
      mark: { show: boolean }
      restore: { show: boolean }
    }
  }
  series: {
    name: string
    type: string
    radius: number[]
    center: string[]
    roseType: string
    itemStyle: {
      borderRadius: number
    }
    data: {
      name: string
      value: number
    }[]
  }[]
} = {
  toolbox: {
    feature: {
      mark: { show: true },
      restore: { show: true }
    }
  },
  series: [
    {
      name: 'Nightingale Chart',
      type: 'pie',
      radius: [10, 100],
      center: ['50%', '50%'],
      roseType: 'area',
      itemStyle: {
        borderRadius: 5
      },
      data: []
    }
  ]
}
onMounted(async () => {
  const getTopicRes = await topicGetTopicListService({ t_uid: userStore.userInfo.id })
  console.log(getTopicRes)
  const getAnnouncementInfoRes = await announcementGetAnnouncementListService()
  topicData.value = getTopicRes.data.data
  announcementData.value = getAnnouncementInfoRes.data.data
  count.value = topicData.value.length
  //统计文章标签数量
  const kind = new Set()
  topicData.value.forEach((item) => {
    kind.add(item.t_kind)
  })
  console.log(kind)
  kindNumber.value = kind.size
  // 统计每种类别的数量
  const kindCount: {
    [key: string]: number
  } = {}
  topicData.value.forEach((item) => {
    if (kindCount[item.t_kind]) {
      kindCount[item.t_kind]++
    } else {
      kindCount[item.t_kind] = 1
    }
  })
  Object.keys(kindCount).forEach((item) => {
    capsuleData.value.push({
      name: item,
      value: kindCount[item]
    })
  })
  capsuleConfig.data = capsuleData.value
  //绘制饼图
  myChart = echarts.init(pieRef.value as HTMLDivElement)
  pieData.value = Object.keys(kindCount).map((item) => {
    return {
      name: item,
      value: kindCount[item]
    }
  })
  console.log(pieData.value)
  option.series[0].data = pieData.value
  myChart.setOption(option)
  window.addEventListener('resize', handleResize)
})
//处理删除公告
const handleDelete = async (e: MouseEvent, id: number) => {
  e.preventDefault()
  await announcementDeleteAnnouncementService(id)
  console.log(id)
  message.success('删除成功')
  const getAnnouncementRes = await announcementGetAnnouncementListService()
  announcementData.value = getAnnouncementRes.data.data
}

const dialogRef = ref<InstanceType<typeof HomeDialog> | null>(null)
const handleShowModal = () => {
  dialogRef.value?.handleShowModal()
}
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="flex flex-col gap-4">
    <NCard class="rounded-2 shadow">
      <div class="flex-col flex lg:flex-row justify-between">
        <div class="flex flex-items-center gap-4">
          <NAvatar
            round
            :size="72"
            :src="userStore.userInfo.avatar || defaultAvatar"
            class="hidden xl:block xl:aspect-ratio-square"
          ></NAvatar>
          <div class="flex flex-col gap-2">
            <n-h3 class="m0">{{ welcome(userStore.userInfo.nickname || '未知用户') }}</n-h3>
            <n-p class="text-gray m0">今天又要干什么呢？</n-p>
          </div>
        </div>
        <div class="flex flex-items-center gap-4">
          <n-statistic label="文章总数" tabular-nums>
            <n-number-animation ref="numberAnimationInstRef" :from="0" :to="count" />
          </n-statistic>
          <n-statistic label="文章标签" tabular-nums>
            <n-number-animation ref="numberAnimationInstRef" :from="0" :to="kindNumber" />
          </n-statistic>
        </div>
      </div>
    </NCard>
    <NGrid cols="1 700:2" x-gap="12" y-gap="12">
      <NGridItem>
        <NCard class="h-100 shadow" hoverable>
          <div class="flex justify-between flex-items-center">
            <n-h4 class="p0 m0">公告</n-h4>
            <n-button type="info" ghost :disabled="!userStore.userInfo.isAdmin" :onclick="handleShowModal">
              发布公告
            </n-button>
          </div>
          <n-divider class="p0 m0" />
          <div class="flex flex-col overflow-auto h-70">
            <div class="flex flex-col m0 p0" v-for="item in announcementData" :key="item.id">
              <div class="flex m0 p0 gap-4 overflow-auto">
                <NAvatar
                  round
                  :size="30"
                  :src="defaultAvatar"
                  class="block aspect-ratio-square"
                ></NAvatar>
                <div class="flex flex-1">
                  <div class="flex flex-col">
                    <h4>{{ item.a_username }}</h4>
                    <p>{{ item.a_content }}</p>
                  </div>
                  <div class="flex flex-col mla">
                    <n-button
                      type="error"
                      ghost
                      :disabled="!userStore.userInfo.isAdmin"
                      :size="'small'"
                      class="w20"
                      :onclick="(e: MouseEvent) => handleDelete(e, item.id)"
                    >
                      <template #icon>
                        <DeleteOutlined />
                      </template>
                      删除
                    </n-button>
                    <p>{{ formatTime(item.a_create_time) }}</p>
                  </div>
                </div>
              </div>
              <n-divider class="m0" />
            </div>
          </div>
        </NCard>
      </NGridItem>
      <NGridItem>
        <NCard class="h-100 shadow" hoverable>
          <n-h4>动态</n-h4>
          <div class="h-80 overflow-auto">
            <n-timeline>
              <n-timeline-item
                v-for="(item, index) in topicData"
                :key="item.id"
                :content="item.t_title"
                :type="index % 2 === 0 ? 'default' : 'info'"
                :time="formatTime(item.create_time)"
              />
            </n-timeline>
          </div>
        </NCard>
      </NGridItem>
      <NGridItem>
        <NCard class="h-90 shadow" hoverable>
          <n-h4>类别条目</n-h4>
          <div class="flex justify-center">
            <CapsuleChart :config="capsuleConfig" style="width: 25rem; height: 15rem" />
          </div>
        </NCard>
      </NGridItem>
      <NGridItem>
        <NCard class="h-90 shadow" hoverable>
          <n-h4>类别占比</n-h4>
          <div class="justify-center">
            <div class="h-75 flex justify-center items-center w-full" ref="pieRef"></div>
          </div>
        </NCard>
      </NGridItem>
    </NGrid>
    <NCard class="p2 shadow" hoverable>
      <n-h4>推荐文章</n-h4>
      <n-carousel direction="vertical" dot-placement="right" mousewheel class="rounded h-100 w-full">
        <img
          v-for="item in topicData.slice(0, topicData.length >= 5 ? 5 : topicData.length)"
          :key="item.id"
          :src="item.t_photo"
          class="rounded w-full h-100 object-cover"
          alt=""
        />
      </n-carousel>
    </NCard>
  </div>
  <HomeDialog
    ref="dialogRef"
    @update:show="
      async () => {
        const getAnnouncementRes = await announcementGetAnnouncementListService()
        announcementData = getAnnouncementRes.data.data
      }
    "
  ></HomeDialog>
</template>
<style scoped>
::-webkit-scrollbar {
  width: 8px;
}

/* 定义滚动条轨道的样式 */
::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

/* 定义滚动条的样式 */
::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

/* 定义滚动条在鼠标悬停时的样式 */
::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
